package com.itlong.cloud.utils.network.https;

import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.utils.node.JsonUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by PPP on 2020/2/12.
 */

public class HttpsPost {
    private static final Logger LOG = LoggerFactory.getLogger(HttpsPost.class);
    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * 绕过验证
     *
     * @return
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

//            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                return null;
//            }
//
//            public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
//                return true;
//            }
//
//            public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
//                return true;
//            }
//
//            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
//                    throws java.security.cert.CertificateException {
//                return;
//            }
//
//            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
//                    throws java.security.cert.CertificateException {
//                return;
//            }
        }};
        // Install the all-trusting trust manager
        try {
//            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            LOG.error("【创建SSL失败】");
        }
    }

    public static String doPost(String token,String url, String sendString) {
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));

        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.addHeader("X-Auth-Token",token);
            StringEntity stringEntity = new StringEntity(sendString,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            System.out.println(stringEntity.getContent());
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }

    public static String doPostV2(String token,String url, String sendString, int timeout) {
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));

        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.addHeader("X-Auth-Token",token);
            StringEntity stringEntity = new StringEntity(sendString,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            System.out.println(stringEntity.getContent());
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }

    public static String doJdPost(String url, String sendString) {
        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(sendString,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            System.out.println(stringEntity.getContent());
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }


    /**
     * <desc>
     *      welink登录
     * </desc>
     *
     * @param accessToken
     * @param url
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/19
     */
    public static String welinkLogin(String accessToken,String url) {
        LOG.info(String.format("\n【华为云调用url】:\n%s;",url));

        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.addHeader("x-wlk-Authorization",accessToken);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }


    /**
     * <desc>
     *      获取welinkAccessToken
     * </desc>
     *
     * @param url
     * @param sendString
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/19
     */
    public static String getWelinkAccessToken(String url, String sendString) {
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));

        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(sendString,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            System.out.println(stringEntity.getContent());
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }

    public static String doGet(String token,String url, String sendString) {
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));
        org.apache.http.client.HttpClient httpClient = null;
        HttpGet httpPost = null;
        String result = null;
        HttpResponse response=null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpGet(url);
            //设置参数
            httpPost.setHeader(new BasicHeader("Accept", "application/json"));
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            httpPost.setHeader(new BasicHeader("X-Auth-Token", token));
            httpPost.setHeader(HttpHeaders.CONNECTION, "close");
            response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            LOG.error("【https ge 失败】");
        }finally {
            if(response!=null) {
                EntityUtils.consumeQuietly(response.getEntity());
            }
            if(httpPost!=null) {
                httpPost.releaseConnection();
            }
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }

    public static  String httpsGetToken(String url, Map<String, Object> params) throws Exception {
        // 构建请求参数
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        String sendString = "";
        JSONObject json = JSONObject.fromObject(params);
        sendString = json.toString();
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));
//        trustAllHosts();
        URL url2 = new URL(url);
        HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();
        try {
            urlCon.setHostnameVerifier(DO_NOT_VERIFY);
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            // 发送POST请求必须设置如下两行
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStream os = urlCon.getOutputStream();
            //参数是键值队  , 不以"?"开始
            os.write(sendString.getBytes());
            //os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes());
            os.flush();
            // 发送请求参数
            //out.print(a);
            // flush输出流的缓冲
            //out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            Map head = urlCon.getHeaderFields();
            String token = head.get("X-Subject-Token").toString();
            result = token.substring(1,token.length()-1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                urlCon.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }

    public static String doPostToken(String url,  Map<String, Object> params) {
       org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            LOG.info(String.format("\n【华为云调用url获取token】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,JsonUtil.toJSON(params)));
            StringEntity stringEntity = new StringEntity(JsonUtil.toJSON(params),"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);

            if (response != null) {
                Header[] a = response.getHeaders("X-Subject-Token");
                LOG.info("【华为云调用url获取token】token={}", a[0].getValue());
                return a[0].getValue();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }



    public static  String httpsGet(String token,String url, String sendString) throws Exception {
        // 构建请求参数
        PrintWriter out = null;
        BufferedReader in = null;
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));
        URL url2 = new URL(url);
        HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();
        try {
//            trustAllHosts();
            urlCon.setHostnameVerifier(DO_NOT_VERIFY);
            urlCon.setRequestMethod("GET");
            urlCon.setRequestProperty("Content-type", "charset=UTF-8");
            urlCon.setRequestProperty("Charset", "UTF-8");
            urlCon.setRequestProperty("X-Auth-Token",token);
            // 发送POST请求必须设置如下两行
//            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            String rsp = null;
            rsp = getResponseAsString(urlCon);
            LOG.info(String.format("【返回结果】：\n%s",rsp));
            return rsp;
        } catch (Exception e) {
            throw e;
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                urlCon.disconnect();
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

//    public static void main(String[] args) throws Exception {
//        while (true) {
//            Thread.sleep(2000);
//            String token = "MIIa5QYJKoZIhvcNAQcCoIIa1jCCGtICAQExDTALBglghkgBZQMEAgEwghj3BgkqhkiG9w0BBwGgghjoBIIY5HsidG9rZW4iOnsiZXhwaXJlc19hdCI6IjIwMjAtMDItMTVUMDc6NDQ6NTIuMDM2MDAwWiIsIm1ldGhvZHMiOlsicGFzc3dvcmQiXSwiY2F0YWxvZyI6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DI2NjIxZmIyYzAxYzQ5OTNjOTJlIn19fTGCAcEwggG9AgEBMIGXMIGJMQswCQYDVQQGEwJDTjESMBAGA1UECAwJR3VhbmdEb25nMREwDwYDVQQHDAhTaGVuWmhlbjEuMCwGA1UECgwlSHVhd2VpIFNvZnR3YXJlIFRlY2hub2xvZ2llcyBDby4sIEx0ZDEOMAwGA1UECwwFQ2xvdWQxEzARBgNVBAMMCmNhLmlhbS5wa2kCCQDcsytdEGFqEDALBglghkgBZQMEAgEwDQYJKoZIhvcNAQEBBQAEggEAmA0D96q4xlWmfj6c6YBwbWa7AQAeb2mx7nUTEGTIKP5tGV2zJ9H4mjJm1LvbV-YdI7VGgEASBgfjS5iaZBeyaP0dDoSjMit+svCy31ts+CaRAIm-ZI0Q3uuo7ZPli7MyA5Af0TzUWJZxjfCP9qk-KmMhx1ha+DUptRGVp5FOpcrSyFZnsdEKgoh2QfTTGe2Z-nPb3Vcv4Xk9DWqsodmlX4QptUE6Qmy9HrvUg2SZVqpYoBI8z1zSn1lf8thNMk3JlGBTWd60iM1yq5Ends4PBBTu3h4XHjTNujy4FIF5ZjGaymfmQr8hxBcoQWRRZTYNLz-fepyeASfwEaP19w2F3Q==";
//            String result = HttpsPost.doGet(token, "https://iotdm.cn-north-4.myhuaweicloud.com/v5/iot/075e638b380025032f5dc01cc8403111/devices/5e437fcf334dd4f3377a4881_0000006010012921964323839049728", null);
//            System.out.println(result);
//        }
//    }

    protected static String getResponseAsString(HttpsURLConnection conn) throws IOException {
        try {
            String charset = getResponseCharset(conn.getContentType());
            InputStream es = conn.getErrorStream();
            if (es == null) {
                return getStreamAsString(conn.getInputStream(), charset);
            } else {
                String msg = getStreamAsString(es, charset);
                if (StringUtils.isEmpty(msg)) {
                    throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
                } else {
                    throw new IOException(msg);
                }
            }
        }catch(Exception e){
            throw e;
        }finally {
            conn.disconnect();
        }
    }

    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();

            char[] chars = new char[256];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }

            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    public static  String https(String token,String url, String sendString) throws Exception {
        // 构建请求参数
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        LOG.info(String.format("\n【华为云调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url,sendString));
//        trustAllHosts();
        URL url2 = new URL(url);
        HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();;
        try {
            urlCon.setHostnameVerifier(DO_NOT_VERIFY);
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            urlCon.setRequestProperty("X-Auth-Token",token);
            // 发送POST请求必须设置如下两行
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStream os = urlCon.getOutputStream();
            //参数是键值队  , 不以"?"开始
            os.write(sendString.getBytes());
            //os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes());
            os.flush();
            // 发送请求参数
            //out.print(a);
            // flush输出流的缓冲
            //out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(urlCon.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw e;
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                urlCon.disconnect();
            } catch (IOException ex) {
                throw ex;
            }
        }
        return result;
    }

    private static String getResponseCharset(String ctype) {
        String charset = PlatformConstants.DEFAULT_CHARSET;

        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (!StringUtils.isEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }

        return charset;
    }


    private static final String ACCEPT = "application/json;charset=utf-8";
    private static final String CONTENT_TYPE_SIMPLE_FORM = "application/x-www-form-urlencoded;charset=utf-8";
    private static final String ENCODING = "utf-8";

    public static String doPost(String url, Map<String,Object> params, int connectionTimeout, int socketTimeout) {
        LOG.info(String.format("\n【调用url】:\n%s;\n===================================================\n【参数】:%s\n===================================================\n",url, com.alibaba.fastjson.JSON.toJSONString(params)));

        HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return false;
            }};

        // 创建httpClient实例.
        HttpClient httpClient;
        HttpPost httpPost;
        String result = null;
        try {
            //采用绕过验证的方式处理https请求
            SSLContext sslcontext = createIgnoreVerifySSL();
            //设置协议http和https对应的处理socket链接工厂的对象
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);

            httpClient  = HttpClients.custom().setConnectionManager(connManager).setRetryHandler(myRetryHandler).build();

            httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", CONTENT_TYPE_SIMPLE_FORM);
            httpPost.setHeader("Accept", ACCEPT);
            //装填参数
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            if(params !=null){
                for (Entry<String, Object> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout)
                    .setConnectionRequestTimeout(5000)
                    .build();
            httpPost.setConfig(requestConfig);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, ENCODING);
                }
            }

        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage());
        } catch (ClientProtocolException e) {
            LOG.error(e.getMessage());
        } catch (IOException e) {
            LOG.error(e.getMessage());
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        LOG.info(String.format("【返回结果】：\n%s",result));
        return result;
    }
    
    /**
     * <desc>
     * 向指定URL发送GET方法的请求
     * </desc>
     *
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @Author chengshican
     * @Date 2020-11-23 11:38
     * @Param url
     * 发送请求的URL
     * @Return
     * @Exception
     */

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    /**
     * <desc>
     * 向指定 URL 发送POST方法的请求
     * </desc>
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @Author chengshican
     * @Date 2020-11-23 11:39
     * @Return
     * @Exception
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}